<template>
    <view class="tabs-box" v-if="computedTabData.length > 0">
        <view class="flex-row-between">
            <view class="flex_1">
                <eui-tab
                    :tabs="computedTabData" 
                    :value="industryTabIndex" 
                    :spaceLeft="spaceLeft" 
                    showBadge
                    badgeType="dot"
                    @change="tabChange"
                    themeColor="rgb(0, 0, 0)"
                    :tabStyle="tabStyle"
                ></eui-tab>
            </view>
            <view class="right-icon" @click="onToTabsList" >
                <text class="iconfont icon-jiantouxiangyou" style="font-size: 10px;"></text>
            </view>
        </view>
        <eui-base-card @click="handleClick" class="flex_1">
            <Email v-if="computedTabData[industryTabIndex].name == '收件箱' && EmailList.length > 0" :data="EmailList"/>
            <Documents v-else-if="computedTabData[industryTabIndex].name == '公文' && DocRecList.length > 0"  :data="DocRecList"/>
            <News v-else-if="computedTabData[industryTabIndex].name == '企业新闻' && NewsList.length > 0" :data="NewsList"/>
            <Knowledge v-else-if="computedTabData[industryTabIndex].name == '知识门户' && KnowledgeList.length > 0" :data="KnowledgeList"/>
        </eui-base-card>
    </view>
</template>
  
<script setup lang="ts">
import dayjs from 'dayjs';
import service from '@/common/service';
import dateRangUtil from '@/common/dateRangUtil';
import Email from '@/pages/BusinessCtrlViews/OaCtrls/TabsEmail.vue';
import News from '@/pages/BusinessCtrlViews/OaCtrls/TabsNews.vue';
import Documents from '@/pages/BusinessCtrlViews/OaCtrls/TabsDocuments.vue';
import Knowledge from '@/pages/BusinessCtrlViews/OaCtrls/TabsKnowledge.vue';
import {storeToRefs} from 'pinia'
import { ref, onMounted, computed, watch, onUnmounted } from 'vue';
import { useRefreshStore } from '@/store/useRefreshStore';
import { useMainStore } from '../../../store/modules/store';
const mainStore = useMainStore();
const { loginInfo } = mainStore;
import { useLoginStore } from '@/store/modules/useLoginStore';
const LoginStore = useLoginStore();
import eventBus from '@/pages/MainViews/eventBus';

/**
 *  HomeTabs 标签页
 */


/**
 * tab 相关处理
 */
const tabStyle = ref({ justifyContent: 'flex-start'});
const tabData = ref([
    { name:'收件箱', corner: 0 }, 
    { name:'公文', corner: 0 },
    { name:'企业新闻', corner: 0 },
    { name:'知识门户', corner: 0 },
]);

// 计算属性，根据列表长度动态生成标签数据
const computedTabData = computed(() => {
  return tabData.value.filter(tab => 
    (tab.name === '收件箱' && EmailList.value.length > 0) ||
    (tab.name === '公文' && DocRecList.value.length > 0) ||
    (tab.name === '企业新闻' && NewsList.value.length > 0) ||
    (tab.name === '知识门户' && KnowledgeList.value.length > 0)
  );
});

const industryTabIndex = ref(0);
const spaceLeft = ref(0);
const tabChange = (data: number)  => {
    industryTabIndex.value = data;
    getData();
}

/**
 * card 相关处理
 */
const handleClick = (data)  => {
    // console.log(data);
    // 请求接口切换数据
}

const onToTabsList = ()  => {
    const label = computedTabData.value[industryTabIndex.value].name;
    let url = ''
    switch (label) {
        case '收件箱':
            url='/pages/OaViews/Email/index'
            break;
        case '企业新闻':
            url='/pages/OaViews/News/index'
            break;
        case '公文':
            url='/pages/OaViews/Document/index';
            break;
        case '知识门户':
            url='/pages/OaViews/Knowledge/index'
            break;
    }
    if (url) {
        uni.navigateTo({
            url
        });
    } else {
        service.enjoyShowToast('点击跳转'+ label + '列表')
    }
}

// 获取收件箱数据 近一个月 前面4条
let OAURL: string = '';
OAURL = LoginStore.EnjoyMain.replace('Enjoy/Service',"File")
const EmailList = ref([])
const QueryEMails = () => {
    service.enjoyShowLoading('正在查询...');
	let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40内部邮件",
			MethodName: "QueryEMails",
            ObjectData: {
                IsNotPage: false,
                Sql: null,
                PageSize: 4,
                CurrentPage: 1,
                c_type: "收件箱",
                c_sender: loginInfo.sUser,
                c_read_status: null, //已读，未读，或全部
                c_title: "",
                c_send_start_dt: dateRangUtil.getLast1Month()[0],
                c_send_end_dt: dateRangUtil.getLast1Month()[2]
            },
		},
	};
    let list:any[] = [];
    service.request(request, (res: any) => {
		if (res && res.data && !res.data.HasException) {
			const objectData = res.data.ObjectData;
			if (objectData && objectData.ReturnObject && objectData.ReturnObject.length > 0) {
                const currentYear = dayjs().year();
                list = objectData.ReturnObject.map((n: any) => {
                    const date = dayjs(n.c_mk_dt);
                    const dateYear = date.year();
                    n.c_send_dt =  dateYear === currentYear ? dayjs(n.c_mk_dt).format('MM-DD HH:mm') : date.format('YYYY-MM-DD HH:mm');
                    n.url = `${OAURL}/DownLoadImage/${n.c_sender}`;
                    return n;
                })
				//新的是用编码N表示未读、Y表示已读
				const _filter = objectData.ReturnObject.filter((item: any) => item.c_read_status=="N" || item.c_read_status=="否");
				tabData.value[0].corner = _filter.length;
			} 
		} else {
            service.enjoyShowToast(res.data.Exception.Message )
        }
        EmailList.value = list;
		service.enjoyHideLoading();
	}, () => {
		service.enjoyHideLoading();
		console.log('失败')
	});
}
// 获取新闻
interface News {
    c_id: string;
    c_guid: string;
    c_mk_dt: string;
    c_title: string;
    c_rev_status: string;
    msgCid: number;
    imgGuid: string;
    itemclass: string;
	littleTitle: string;
}

const NewsList = ref<News[]>([]);
const GetNewsCarouseltList = ()  => {
    service.enjoyShowLoading('正在查询...');
    let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40主页",
			MethodName: "GetNewsCarouseltList",
            ObjectData: loginInfo.sUser,
		},
	};
    let list:any[] = [];
    service.request(request, (res: any) => {
        if (res && res.data && !res.data.HasException) {
            const objectData = res.data.ObjectData;
            
            if (objectData && objectData.length > 0) {
                const currentYear = dayjs().year();
                list = objectData.map((n: document) => {
                    const date = dayjs(n.c_mk_dt);
                    const dateYear = date.year();
                    n.c_mk_dt = dateYear === currentYear ? dayjs(n.c_mk_dt).format('MM-DD HH:mm') : date.format('YYYY-MM-DD HH:mm');
                    return n;
                });
				
				
				if(list && list.length>0)
				{
					//删除最后两个，最后两个是服务端做了特殊处理用于轮播图展示的，这里列表展示不需要最后两个
					list.pop();
					list.pop()
				}
            }
            const _filter = res.data.ObjectData.filter((item: any) => item.c_rev_status == "N");
            tabData.value[2].corner = _filter.length;
            
        } else {
            service.enjoyShowToast(res.data.Exception.Message || '')
        }
		NewsList.value = list || [];
        service.enjoyHideLoading();
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}


// TODO 获取公文只取前4条
interface document { 
    c_bill_name?: string;
    c_dt?: string;
    c_extend_key?: string;
    c_item_type?: string;
    c_id: number | string,
    c_title: string;
    c_status: string;
    [key: string]: any; 
}
const DocRecList = ref<document[]>([]);
const GetDocRecList = ()  => {
    service.enjoyShowLoading('正在查询...');
    let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40企业新闻",
			MethodName: "GetDocRecList",
            ObjectData: {
                title: "",
                userno: loginInfo.sUser,
                sdt: dateRangUtil.getLast1Month()[0],
                edt: dateRangUtil.getLast1Month()[2]
            },
		},
	};
    let list:any[] = [];
    service.request(request, (res: any) => {
        if (res && res.data && !res.data.HasException) {
            const objectData = res.data.ObjectData;
            if (objectData && objectData.length > 0) {
                const currentYear = dayjs().year();
                list = res.data.ObjectData.map((n: document) => {
                    const date = dayjs(n.c_dt);
                    const dateYear = date.year();
                    n.c_dt = dateYear === currentYear ? dayjs(n.c_dt).format('MM-DD') : date.format('MM-DD HH:mm');
                    n.docType = n.c_doc_name ? n.c_doc_name.split('.').pop()+'.png' : "gw_mrt.png";
                    return n;
                })
                const _filter = res.data.ObjectData.filter((item: any) => item.c_status == "NV");
                tabData.value[1].corner = _filter.length;
            }

        } else {
            service.enjoyShowToast(res.data.Exception.Message || '')
        }
		DocRecList.value = list || [];
        service.enjoyHideLoading();
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}
// 获取知识中心
interface Knowledge { 
    c_number?: string | number;
    c_file_name?: string;
    c_id?: string;
    c_guid?: string;
    c_type?: string;
    c_mk_dt?: string;
    c_mk_username?: string;
    c_title?: string;
    c_cname?: string;
    c_doc_size?: string;
    c_downread_num?: string | number;
    c_docimg_url?: string;
    c_link?: string;
    [key: string]: any; 
}

//const baseUrl = EnjoyBaseURL.value.EnjoyMain.indexOf('http') >= 0 ? '' : EnjoyBaseURL.value.EnjoyMain;
const KnowledgeList = ref<any[]>([]);
const GetKnowLedgeNewList = () => {
    service.enjoyShowLoading('正在查询...');
	let request = {
		url: LoginStore.EnjoyMain, 
		data: {
			UniqueKey: "管易通40知识中心",
			MethodName: "GetKnowLedgeNewList",
            ObjectData: {
                IsNotPage: true,
                sqlWhereTail: ' ORDER BY c_mk_dt desc ',
            }
		},
	};
	
	let list:any[] = [];
    service.request(request, (res: any) => {
		if (res && res.data && !res.data.HasException) {
			const objectData = res.data.ObjectData;
			if (objectData && objectData.length > 0) {
                list = objectData.map((item: Knowledge) => ({
                    ...item,
                    c_mk_dt: dayjs(item.c_mk_dt).format('YYYY-MM-DD'),
                    c_download_count: item.c_type == '文件' ? item.c_download_count : item.c_read_count,
                    c_docimg_url: item.c_type == "在线编辑" ? 'xml.png' : getDocImgType(item.c_file_name),
                    filePath: `${OAURL}/DownLoadFile/${item.c_guid}`,
                }));

                const _filter = res.data.ObjectData.filter((item: any) => item.c_read_count === 0 && item.c_download_count);
                tabData.value[3].corner = _filter.length;
			} 
		} else {
            service.enjoyShowToast(res.data.Exception.Message )
        }
       
		KnowledgeList.value = list || [];
		service.enjoyHideLoading();
	}, () => {
		service.enjoyHideLoading();
		console.log('失败')
	});
}

const getDocImgType = (docName: string): string => {
  if (!docName) {
    return 'spl.png';
  }

  const fix: string = docName.substring(docName.lastIndexOf('.') + 1).toLowerCase();

  switch (fix) {
    case 'doc':
    case 'docx':
      return 'docx.png';
    case 'txt':
      return 'txt.png';
    case 'ppt':
    case 'pptx':
      return 'pptx.png';
    case 'jpg':
    case 'png':
    case 'bmp':
    case 'jpeg':
    case 'gif':
      return 'picture.png';
    case 'exe':
      return 'exe.png';
    case 'pdf':
      return 'pdf.png';
    case 'avi':
    case 'wma':
    case 'rmvb':
    case 'mp4':
    case 'mov':
    case 'mpeg':
    case 'flv':
    case 'asf':
      return 'video.png';
    case 'html':
    case 'xml':
      return 'xml.png';
    case 'xls':
    case 'xlsx':
    case 'xlsm':
      return 'xlsx.png';
    default:
      return 'spl.png';
  }
};



/** 数据处理 */
const getData = (isFirstIn: boolean)  => {
    console.log(405, isFirstIn);
	if(isFirstIn === true){
		QueryEMails();
		GetNewsCarouseltList();
		GetDocRecList();
		GetKnowLedgeNewList();
	} else {
		const label = computedTabData.value[industryTabIndex.value].name;
		if (label == '收件箱') {
			QueryEMails();
		} else if (label == "企业新闻") {
			GetNewsCarouseltList();
		} else if (label == "公文") {
			GetDocRecList();
		} else if (label == "知识门户") {
			GetKnowLedgeNewList()
		}
	}
}

const homeStore = useRefreshStore();
watch(() => homeStore.refreshTrigger, (newVal: any, oldValue: any) => {
    // console.log('watch监听的数据刷新了啊!!!!!!!!!!!!!!!!!!!', newVal, oldValue, homeStore.refreshType);
    if (newVal && homeStore.refreshType == 'HomeRefresh') {
        getData(true);
    }
  }
);
const eventBusRefresh = () => {
    GetNewsCarouseltList();
}
onMounted(() => {
    getData(true);
    eventBus.on('refresh-HomeTabs', () => getData(true));
    eventBus.on('refresh-EmailList', QueryEMails);
    eventBus.on('refresh-NEWSList', eventBusRefresh);
    eventBus.on('refresh-DocRecList', GetDocRecList);
    eventBus.on('refresh-KnowledgeList', GetDocRecList);
});

onUnmounted(() => {
    eventBus.off('refresh-HomeTabs', () => getData);
    eventBus.off('refresh-EmailList', QueryEMails);
    eventBus.off('refresh-NEWSList', eventBusRefresh);
    eventBus.off('refresh-DocRecList', GetDocRecList);
    eventBus.off('refresh-KnowledgeList', GetDocRecList);
});

</script>
<style lang="scss" scoped>
.tabs-box {
  margin-bottom: 20rpx;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 20rpx;
  ::v-deep .rds-tabs .tab-item.active {
    font-family: PingFangSC, PingFang SC;
    font-size: 32rpx;
    font-weight: 600;
    color: #000000;
  }
  ::v-deep .rds-tabs .selectdLine {
    background-color: #000000 !important;
}
}
.right-icon {
    padding-right: 28rpx;
    height: 88rpx;
    line-height: 88rpx;
    color: #888888;
}

</style>